<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="患者姓名" prop="username" style="width: 200px;">
        <el-input
            v-model="queryParams.username"
            placeholder="请输入患者姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="手机号码" prop="phonenumber" style="width: 200px;">
        <el-input
            v-model="queryParams.phonenumber"
            placeholder="请输入手机号码"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="性别" prop="sex" style="width: 200px;">
        <el-select v-model="queryParams.sex" placeholder="请选择性别" clearable>
          <el-option
              v-for="dict in sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
        v-loading="loading"
        :data="userList"
        @selection-change="handleSelectionChange"
        row-key="userId"
        :expand-row-keys="expandRowKeys"
        @row-click="handleRowClick"
        style="width: 100%"
    >
      <el-table-column type="selection" width="55" align="center"/>

      <el-table-column type="expand">
        <template #default="{ row }">
          <div v-if="row.subItems && row.subItems.length" class="sub-items-container">
            <div class="sub-title">历史咨询记录：</div>
            <!-- 嵌套表格展示子项 -->
            <el-table :data="row.subItems" border style="width: 100%" class="nested-table">
              <el-table-column label="预约结束时间" prop="endTime" width="180">
                {{ parseTime(row.endTime) }}
              </el-table-column>
              <el-table-column label="主诉内容" prop="mainProblem"/>
              <el-table-column label="风险等级" prop="riskAssessment" width="90" align="right">
                <template #default="{ row }">
                  <dict-tag :options="risk_level" :value="row.riskAssessment"/>
                </template>
              </el-table-column>
              <el-table-column label="状态" prop="appointmentStatus"  width="90" align="right">
                <template #default="{ row }">
                  <dict-tag :options="appointment_status" :value="row.appointmentStatus"/>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div v-else class="no-data">暂无更多咨询记录</div>
        </template>
      </el-table-column>
      <el-table-column label="患者ID" align="center" prop="userId"/>
      <el-table-column label="患者姓名" align="center" prop="username"/>
      <el-table-column label="手机号码" align="center" prop="phonenumber"/>
      <el-table-column label="用户邮箱" align="center" prop="email"/>
      <el-table-column label="性别" align="center" prop="sex">
        <template #default="scope">
          <dict-tag :options="sys_user_sex" :value="scope.row.sex"/>
        </template>
      </el-table-column>

      <el-table-column label="头像" align="center" prop="userAvatar">
        <template #default="scope">
          <image-preview :src="scope.row.userAvatar" alt="头像" style="width: 50px; height: 50px; border-radius: 50%;"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
  </div>
</template>


<script setup name="User">

import ImagePreview from "@/components/ImagePreview/index.vue";
import {onMounted, ref} from "vue";
import {getPatineList} from "@/api/appointment/appointment.js";
import DictTag from "@/components/DictTag/index.vue";
import {parseTime} from "@/utils/ruoyi.js";

const {proxy} = getCurrentInstance();

const {
  sys_user_sex,
  appointment_status,
  risk_level
} = proxy.useDict('sys_user_sex', 'appointment_status', 'risk_level');

const userList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const expandRowKeys = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    username: null,
    phonenumber: null,
    sex: null,
  },
  rules: {}
});

const {queryParams, form, rules} = toRefs(data);

const handleRowClick = (row) => {
  // 只在点击主记录时触发展开
  if (row.isMainRecord) {
    toggleExpand(row)
  }
}

function isExpanded(row) {
  return expandRowKeys.value.includes(row.userId)
}

const toggleExpand = (row) => {
  const currentKeys = [...expandRowKeys.value]
  const index = currentKeys.indexOf(row.userId)

  if (index > -1) {
    // 如果已展开则收起
    currentKeys.splice(index, 1)
  } else {
    // 清空数组实现单行展开
    currentKeys.length = 0
    currentKeys.push(row.userId)
  }

  expandRowKeys.value = currentKeys
}

/** 查询用户信息列表 */
const getList = () => {
  loading.value = true
  console.log("查询条件：", queryParams.value)
  getPatineList(queryParams.value).then(response => {
    const groupedData = {}

    response.rows.forEach(item => {
      if (!groupedData[item.userId]) {
        // 主记录：第一个遇到的记录作为主显示数据
        groupedData[item.userId] = {
          ...item,
          subItems: [],    // 子项数组
          isMainRecord: true // 标记为主记录
        }
      } else {
        // 子项：后续相同用户的记录存入subItems
        groupedData[item.userId].subItems.push(item)
      }
    })

    // 转换对象为数组并处理子项排序
    userList.value = Object.values(groupedData).map(user => ({
      ...user,
      // 对子项按时间倒序排列
      subItems: user.subItems.sort((a, b) =>
          new Date(b.endTime) - new Date(a.endTime))
    }))

    total.value = response.total
    console.log("响应数据", response)
    loading.value = false
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}


/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}


// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.userId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}


/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/user/export', {
    ...queryParams.value
  }, `user_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
})
</script>
<style scoped>
.nested-table th,
.nested-table td {
  text-align: center !important;
}

.sub-items-container .sub-title {
  font-size: 16px;
  color: #409EFF;
  font-weight: bold;
  margin-bottom: 8px;
  text-align: center;
}

.no-data {
  text-align: center;
  font-size: 16px;
  color: #999;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
  margin: 10px;
}
</style>
